#!/usr/bin/env python
#
#    Musashi - A project manager for music groups and bands
#    Copyright (C) 2010 Daniel Torres
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# This script grabs an output sql script generated through MySQLWorkbench  using
# the supplied schema.mwb file, and adapts it to be used with Musashi.
#
# Syntax:
#   processDB -f myFile.sql
#

import optparse
import os
import re

#
# Installation script function
#
def processInstallScript( lines, outputFilename, tablePrefix, engine ):
    """Based on the provided input, generates a Musashi-valid installation file"""
    
    # Create ouput file
    output = open( outputFilename, "wt" )
    
    # Needed patterns
    pCreate = re.compile('^CREATE SCHEMA')
    pUse    = re.compile(r'^USE\b')
    pTable  = re.compile(r'Musashi`.`')
    pEngine = re.compile(r'(^ENGINE\s*=\s*)[a-zA-Z;]+')
    pCmt    = re.compile(r'^COMMENT')
    
    pNewEngine = r'\1' + engine + ';'
    
    # Process
    for line in lines:
        
        line = pCreate.sub('-- CREATE SCHEMA', line)
        line = pUse.sub('-- USE', line)
        line = pTable.sub(tablePrefix,line)
        line = pEngine.sub(pNewEngine,line)
        line = pCmt.sub('-- COMMENT',line)
        
        output.write(line)
    
    output.close()   
    return;


#
# Uninstall script function
#
def processUninstallScript( lines, outputFilename, tablePrefix ):
    """Based on the provided input, generates a Musashi-valid uninstallation script file"""

    # Create ouput file
    output = open( outputFilename, "wt" )
    
    # Needed patterns
    pCmnt  = re.compile('^-- (-)+$')
    pTCmnt = re.compile('^-- Table')
    pDrop  = re.compile('^DROP TABLE')    
    pTable = re.compile(r'Musashi`.`')
    
    
    # Process
    for line in lines:
        if pCmnt.match(line):
            output.write(line)
            continue
            
        if pTCmnt.match(line) or pDrop.match(line):
            line = pTable.sub(tablePrefix,line)
            output.write(line)
        
    output.close()

    return;

# Parse input
parser = optparse.OptionParser()
parser.add_option("-f", "--file", dest="input", help="Input sql file")
parser.add_option("-i", "--install", dest="install", help="Install filename", default="install.sql")
parser.add_option("-u", "--uninstall", dest="uninstall", help="Uninstall filename", default="uninstall.sql")
parser.add_option("-p", "--prefix", dest="prefix", help="database prefix name", default="#__Musashi_")
parser.add_option("-e", "--engine", dest="engine", help="Desired database engine", default="MyISAM")

# parse arguments. We must have, at least, the input filename
(options,args) = parser.parse_args();
if options.input == None:
    print "Insufficient parameters: Must provide at least an input filename"
    exit()
    
# Read the input filename
try:
    file  = open(options.input, "r")
    lines = file.readlines()
    file.close()
except IOError:
    print "Error reading: " + options.input + ", make sure the file exists and is accessible"
    exit()
    
# Now that we have the file, process two new ones: Installation and Uninstallation scripts.
processInstallScript( lines, options.install, options.prefix, options.engine )
processUninstallScript( lines, options.uninstall, options.prefix )

